
# api sign sdk between client and server

import hashlib
import time
import requests
import json

INTERVAL = 60 * 5


class pihsdk:
    def __init__(self, key, device, host):
        self.key = key
        self.host = host
        self.device = device
        
    def sign(self, timestamp, content=''):
        tmp_str = self.key + '_' + str(timestamp) + '_' + content
        #print(tmp_str)
        return hashlib.md5(tmp_str.encode('utf8')).hexdigest()

    def send_get(self, tar_url):
        cur_ts = int(time.time())
        tmp_url = self.host + tar_url + '?ts=%d&sign=%s' % (cur_ts, self.sign(cur_ts)) 
        #print(tmp_url)
        response = requests.get(tmp_url)
        return response.json()
    
    def send_post(self, tar_url, content):
        cur_ts = int(time.time())
        #print(content)
        tmp_url = self.host + tar_url + '?ts=%d&sign=%s' % (cur_ts, self.sign(cur_ts, json.dumps(content)))
        response = requests.post(tmp_url, data=json.dumps(content))
        #print(response.text)
        return response.json()

    def send_url(self, tar_data):
        resItem = {
            'status': 1, 
            'device': self.device,
            'data': tar_data
        }
        return self.send_post('/newurl', resItem)
    
    def get_url(self):
        return self.send_get('/getpage')
    
    def send_page(self, tar_data):
        resItem = {
            'status': 1, 
            'device': self.device,
            'data': tar_data
        }
        return self.send_post('/submitpage', resItem)
        
        
    


def check_sign(tar_sign, key, timestamp, content=''):
    cur_ts = time.time()
    
    if cur_ts - int(timestamp) > INTERVAL:
        return False
    #print(type(key))
    #print(type(timestamp))
    if isinstance(content, bytes):
        content = str(content,'utf-8')
    tmp_str = key + '_' + str(timestamp) + '_' + content
    #print(tmp_str)
    tmp_sign = hashlib.md5(tmp_str.encode('utf8')).hexdigest()
    #print(tmp_sign)
    #print(tar_sign)
    #print(tmp_sign == tar_sign)
    return tmp_sign == tar_sign